package com.lplb.common.coreconfig.config;

import com.lplb.common.core.result.RType;
import com.lplb.common.core.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * ID 参数验证器
 * @author wangsong
 * @mail 1720696548@qq.com
 * @date 2020/7/20 0020 9:12 
 * @version 1.0.0
 */
@Component
@Aspect
@Slf4j
public class IdVerificationAspect {


    /**
     * 判断add方法是否勿传Id参数（不传Id, 空字符串也不允许）
     * @param proceed
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.lplb.*..*.add(..))")
    public Object add(ProceedingJoinPoint proceed) throws Throwable {
        Object id = JsonUtil.parseMap(proceed.getArgs()[0]).get("id");
        log.info("判断add方法是否勿传Id参数 ==> id:{}", id);
        if (id != null) {
            throw new ErrorException(RType.SYS_ERROR_PARAM, "Add do not pass ID parameter");
        }
        return proceed.proceed();
    }


    /**
     * 判断所有添加数据方法是否勿传Id参数（必传Id，不能传递空字符串）
     * @param proceed
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.lplb.*..*.upd(..))")
    public Object upd(ProceedingJoinPoint proceed) throws Throwable {
        Object id = JsonUtil.parseMap(proceed.getArgs()[0]).get("id");
        log.info("判断upd方法是否传递Id参数 ==> id:{}", id);
        if (id == null || "".equals(id)) {
            throw new ErrorException(RType.SYS_ERROR_PARAM, "The modification must pass the ID parameter");
        }
        return proceed.proceed();
    }


    /**
     * 判断 findId 方法是否传递Id参数
     * @param proceed
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.lplb.*..*.findId(..))")
    public Object findId(ProceedingJoinPoint proceed) throws Throwable {
        Object id = proceed.getArgs()[0];
        log.info("判断findId方法是否传递Id参数 ==> id:{}", id);
        if (id == null || "".equals(id)) {
            throw new ErrorException(RType.SYS_ERROR_PARAM, "没有Id");
        }
        return proceed.proceed();
    }


    /**
     * 判断removeId方法是否传递Id参数
     * @param proceed
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.lplb.*..*.removeId(..))")
    public Object removeId(ProceedingJoinPoint proceed) throws Throwable {
        Object id = proceed.getArgs()[0];
        log.info("判断removeId方法是否传递Id参数 ==> id:{}", id);
        if (id == null || "".equals(id)) {
            throw new ErrorException(RType.SYS_ERROR_PARAM, "没有Id");
        }
        return proceed.proceed();
    }
}



